<template>
  <section id="team" class="py-24 bg-gray-50" :style="{ '--primary-color': primaryColor }">
    <div class="container mx-auto px-4 sm:px-6 lg:px-8">
      <!-- 标题区域 -->
      <div class="text-center max-w-3xl mx-auto mb-16">
        <span class="text-primary font-medium">专业团队</span>
        <h2 class="text-[clamp(1.75rem,4vw,2.5rem)] font-bold mt-2 mb-4">认识我们的核心团队</h2>
        <p class="text-gray-600 text-lg leading-relaxed">由行业资深专家组成的团队，拥有丰富的实战经验和专业知识</p>
      </div>

      <!-- 加载状态 -->
      <div v-if="isLoading" class="flex flex-col items-center justify-center py-16 bg-white rounded-xl shadow-sm">
        <div class="w-12 h-12 border-4 border-gray-200 border-t-primary rounded-full animate-spin mb-4"></div>
        <p class="text-gray-600">正在加载团队成员信息...</p>
      </div>

      <!-- 团队成员列表 -->
      <div v-else class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-8">
        <div v-for="(member, index) in teamMembers" :key="index"
          class="bg-white rounded-xl overflow-hidden shadow-md transition-all duration-300 hover:-translate-y-1 hover:shadow-xl cursor-pointer">
          <div class="relative">
            <img :src="member.avatar" :alt="`${member.name} - ${member.position}`"
              class="w-full h-80 object-cover object-center">
            <div class="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/70 to-transparent p-4">
              <h3 class="text-white font-bold text-lg">{{ member.name }}</h3>
              <p class="text-white/80 text-sm">{{ member.position }}</p>
            </div>
          </div>
          <div class="p-6">
            <p class="text-gray-600 text-sm mb-4">{{ member.bio }}</p>
            <div class="flex space-x-3">
              <a v-for="(social, sIndex) in member.socialLinks" :key="sIndex" :href="social.link"
                :title="`${social.name}主页`"
                class="w-8 h-8 rounded-full bg-gray-100 flex items-center justify-center text-gray-600 hover:bg-primary hover:text-white transition-all duration-300"
                target="_blank" rel="noopener noreferrer">
                <i :class="['fa', social.icon]"></i>
              </a>
            </div>
          </div>
        </div>
      </div>

      <!-- 公司文化 -->
      <div class="mt-20">
        <h3 class="text-2xl font-bold text-center mb-12">我们的企业文化</h3>
        <div class="grid grid-cols-1 md:grid-cols-3 gap-8">
          <div v-for="(value, index) in cultureValues" :key="index"
            class="bg-white p-8 rounded-xl text-center hover:shadow-lg transition-all duration-300">
            <div class="w-16 h-16 bg-primary/10 rounded-full flex items-center justify-center mx-auto mb-6">
              <i :class="['fa', value.icon, 'text-2xl text-primary']"></i>
            </div>
            <h4 class="text-xl font-bold mb-3">{{ value.title }}</h4>
            <p class="text-gray-600">{{ value.description }}</p>
          </div>
        </div>
      </div>

      <!-- 刷新按钮（仅在有数据源时显示） -->
      <div v-if="dataSourceUrl && !isLoading" class="flex justify-end mt-8">
        <button @click="refreshData" :style="{ backgroundColor: primaryColor }"
          class="px-4 py-2 text-white rounded-lg hover:opacity-90 transition-all duration-300 flex items-center"
          :disabled="isLoading">
          <i class="fa fa-refresh mr-2"></i>
          刷新团队信息
        </button>
      </div>
    </div>
  </section>
</template>

<script>
export default {
  name: 'TeamSection',
  // 低代码平台元数据
  lowcode: {
    // 组件基本信息
    meta: {
      name: 'team-section',
      displayName: '团队介绍',
      description: '展示团队成员信息和企业文化的组件',
      icon: 'fa-users',
      category: '内容展示',
      version: '1.0.0',
      isContainer: false
    },

    // 配置面板结构
    configPanel: [
      {
        title: '基本配置',
        fields: [
          {
            name: 'primaryColor',
            label: '主题色',
            type: 'color',
            defaultValue: '#165DFF'
          }
        ]
      },
      {
        title: '布局配置',
        fields: [
          {
            name: 'columnLayout',
            label: '列布局',
            type: 'select',
            options: [
              { label: '自动适应', value: 'auto' },
              { label: '1列', value: '1' },
              { label: '2列', value: '2' },
              { label: '3列', value: '3' },
              { label: '4列', value: '4' }
            ],
            defaultValue: 'auto'
          },
          {
            name: 'cardStyle',
            label: '卡片风格',
            type: 'select',
            options: [
              { label: '默认', value: 'default' },
              { label: '简约', value: 'simple' },
              { label: '阴影', value: 'shadow' }
            ],
            defaultValue: 'default'
          }
        ]
      },
      {
        title: '数据源配置',
        fields: [
          {
            name: 'dataSourceUrl',
            label: 'API数据源URL',
            type: 'text',
            description: 'API接口的地址',
            defaultValue: ''
          },
          {
            name: 'autoLoad',
            label: '自动加载',
            type: 'boolean',
            defaultValue: true
          }
        ]
      }
    ],

    // 暴露的事件
    events: [
      {
        name: 'memberClick',
        label: '成员卡片点击',
        description: '点击团队成员卡片时触发',
        parameters: [
          { name: 'member', type: 'object', description: '成员信息对象' }
        ]
      },
      {
        name: 'socialLinkClick',
        label: '社交链接点击',
        description: '点击社交链接时触发',
        parameters: [
          { name: 'link', type: 'string', description: '链接地址' },
          { name: 'platform', type: 'string', description: '平台名称' }
        ]
      },
      {
        name: 'dataLoaded',
        label: '数据加载完成',
        description: '从API数据源加载团队成员数据完成时触发',
        parameters: [
          { name: 'teamMembers', type: 'array', description: '加载的团队成员数据' }
        ]
      },
      {
        name: 'dataLoadError',
        label: '数据加载失败',
        description: '从API数据源加载团队成员数据失败时触发',
        parameters: [
          { name: 'error', type: 'object', description: '错误信息' }
        ]
      }
    ],

    // 支持的动作
    actions: [
      {
        name: 'refreshData',
        label: '刷新数据',
        description: '重新加载团队成员数据'
      }
    ]
  },
  props: {
    // 主题色配置
    primaryColor: {
      type: String,
      default: '#165DFF'
    },

    children: {
      type: Array,
      default: () => []
    },
    // 数据源配置
    dataSourceUrl: {
      type: String,
      default: ''
    },
    autoLoad: {
      type: Boolean,
      default: true
    },
    // 企业文化价值观数据
    cultureValues: {
      type: Array,
      default: () => ([
        {
          icon: 'fa-lightbulb-o',
          title: '创新进取',
          description: '不断探索新技术、新方法，勇于创新，追求卓越，为客户创造更大价值。'
        },
        {
          icon: 'fa-users',
          title: '合作共赢',
          description: '尊重每一位团队成员和客户，建立良好合作关系，实现共同发展和进步。'
        },
        {
          icon: 'fa-handshake-o',
          title: '客户至上',
          description: '以客户需求为导向，提供优质服务和解决方案，与客户建立长期稳定的合作关系。'
        }
      ])
    },

    // 团队成员数据（可从外部传入）
    teamMembers: {
      type: Array,
      default: () => ([
        {
          name: '张明',
          position: '创始人兼CEO',
          avatar: 'https://picsum.photos/seed/team1/400/500',
          bio: '前IBM高级工程师，20年企业信息化经验，曾主导多个大型企业数字化转型项目。',
          socialLinks: [
            { name: 'LinkedIn', icon: 'fa-linkedin', link: '#' },
            { name: 'Twitter', icon: 'fa-twitter', link: '#' },
            { name: 'Email', icon: 'fa-envelope', link: '#' }
          ]
        },
        {
          name: '李娜',
          position: '技术总监',
          avatar: 'https://picsum.photos/seed/team2/400/500',
          bio: '前微软技术架构师，15年软件开发经验，专注于企业级应用架构设计与实现。',
          socialLinks: [
            { name: 'LinkedIn', icon: 'fa-linkedin', link: '#' },
            { name: 'Twitter', icon: 'fa-twitter', link: '#' },
            { name: 'Email', icon: 'fa-envelope', link: '#' }
          ]
        },
        {
          name: '王强',
          position: '产品总监',
          avatar: 'https://picsum.photos/seed/team3/400/500',
          bio: '拥有12年企业软件产品设计经验，擅长将业务需求转化为创新的产品解决方案。',
          socialLinks: [
            { name: 'LinkedIn', icon: 'fa-linkedin', link: '#' },
            { name: 'Twitter', icon: 'fa-twitter', link: '#' },
            { name: 'Email', icon: 'fa-envelope', link: '#' }
          ]
        },
        {
          name: '陈静',
          position: '销售总监',
          avatar: 'https://picsum.photos/seed/team4/400/500',
          bio: '10年企业软件销售经验，深入理解各行业客户需求，为客户提供最佳解决方案。',
          socialLinks: [
            { name: 'LinkedIn', icon: 'fa-linkedin', link: '#' },
            { name: 'Twitter', icon: 'fa-twitter', link: '#' },
            { name: 'Email', icon: 'fa-envelope', link: '#' }
          ]
        }
      ])
    },
    // 新增布局相关配置
    columnLayout: {
      type: String,
      default: 'auto'
    },
    cardStyle: {
      type: String,
      default: 'default'
    },
    // 数据源绑定支持
    dataSource: {
      type: [Array, String],
      default: null
    },
    // 更多样式定制
    cardRadius: {
      type: Number,
      default: 8
    },
    shadowDepth: {
      type: Number,
      default: 2
    }
  },

  data() {
    return {
      // 加载状态
      isLoading: false,
      // 原始数据备份
      originalTeamMembers: []
    };
  },

  mounted() {
    // 保存原始数据，用于恢复
    this.originalTeamMembers = JSON.parse(JSON.stringify(this.teamMembers));

    // 自动加载数据
    if (this.autoLoad && this.dataSourceUrl) {
      this.loadDataFromSource();
    }
  },

  watch: {
    // 当teamMembers数据变化时，同步更新原始数据备份
    teamMembers: {
      handler(newVal) {
        this.originalTeamMembers = JSON.parse(JSON.stringify(newVal));
      },
      deep: true,
      immediate: true
    },

    // 当数据源URL变化时，重新加载数据
    dataSourceUrl(newUrl) {
      if (this.autoLoad && newUrl) {
        this.loadDataFromSource();
      }
    }
  },

  methods: {
    /**
     * 从API数据源加载数据
     */
    async loadDataFromSource() {
      if (!this.dataSourceUrl) {
        this.$emit('dataLoadError', { message: '数据源URL不能为空' });
        return;
      }

      this.isLoading = true;

      try {
        const response = await fetch(this.dataSourceUrl, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json'
          }
        });

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data = await response.json();

        // 验证数据格式
        if (!Array.isArray(data)) {
          throw new Error('数据格式错误：返回的不是数组');
        }

        // 使用对象展开运算符创建新对象，确保响应式
        this.$props.teamMembers = [...data];

        this.$emit('dataLoaded', data);
      } catch (error) {
        console.error('加载团队成员数据失败:', error);
        this.$emit('dataLoadError', error);
      } finally {
        this.isLoading = false;
      }
    },

    /**
     * 恢复原始数据
     */
    restoreOriginalData() {
      this.$props.teamMembers = JSON.parse(JSON.stringify(this.originalTeamMembers));
    },

    // 新增事件触发方法
    handleMemberClick(member) {
      this.$emit('memberClick', member);
    },
    handleSocialLinkClick(link, platform, e) {
      this.$emit('socialLinkClick', link, platform);
      // 支持平台配置是否阻止默认行为
      if (this.preventDefault) {
        e.preventDefault();
      }
    },

    // 新增动作实现
    refreshData() {
      if (this.dataSourceUrl) {
        this.loadDataFromSource();
      }
    }
  }

};
</script>

<style scoped>
/* 已替换为Tailwind CSS样式 */
</style>